﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Easy.Chat
{
    public class Conversation
    {
        public int ID { get; set; }
        public bool Init { get; set; }
        public List<PMessage> PM { get; set; }
        public string UserName { get; set; }
        public string Creator { get; set; }

        public Conversation(string userName, string creator)
        {
            this.Init = false;
            this.UserName = userName;
            this.Creator = creator;
            this.PM = new List<PMessage>();
        }

        public void InitMsg()
        {
            this.PM = PMessage.GetByConversationID(this.ID);
        }


        public List<string> GetAllOtherNames(string myLoginName)
        {
            List<string> otherNames = new List<string>();
            if (this.UserName != myLoginName)
            {
                otherNames.Add(this.UserName);
            }
            if (this.Creator != myLoginName)
            {
                otherNames.Add(this.Creator);
            }

            return otherNames;
        }
        private static List<Conversation> _inMemoryConver = new List<Conversation>();

        public static List<Conversation> GetAllMyConversation(string userName)
        {
            List<Conversation> convers = _inMemoryConver.Where(c => c.UserName == userName || c.Creator == userName).ToList();
            foreach(Conversation conver in convers)
            {
                conver.InitMsg();
            }

            return convers;
        }
        public static Conversation GetByID(int id)
        {
            return _inMemoryConver.Where(m => m.ID == id).FirstOrDefault();
        }

        public static void Add(Conversation conver)
        {
            lock (_inMemoryConver)
            {
                conver.ID = _inMemoryConver.Count + 1;
                _inMemoryConver.Add(conver);
            }
        }

        public static Conversation Get(string userName1, string userName2)
        {
            return _inMemoryConver.Where(c => (c.UserName == userName1 && c.Creator == userName2)
                || (c.UserName == userName2 && c.Creator == userName1)).FirstOrDefault();
        }


    }
}
